# 读取图片,做相应预处理
img = Image.open('./house.jpg') 

# 将读入的图片转化为float32类型的numpy.ndarray,
# 图片读入成ndarry时,形状是[H, W, 3],
x = np.array(img).astype('float32')#(282, 378, 3) 

# 将图片形状调整为[N, C, H,W]的格式,以满足 nn.conv2d数据格式
x = np.transpose(x, (2, 0, 1))
x = x[np.newaxis, :]
x = torch.Tensor(x) #(1,3,282,378) # 输入 [N, C, H, W]
conv = nn.Conv2d(in_channels=3,
                     out_channels=1,
                     kernel_size=(3,3),
                     stride = 1)
# Conv:[out, in, H, W]  

# 设置初始值
w = np.array([[-1, -1, -1],
                 [-1, 8, -1],
                 [-1, -1, -1]], dtype='float32')
w = w.reshape(1, 1, 3, 3)
w = np.repeat(w, 3, axis=1)
w = torch.Tensor(w)  # W:(out_channels, in_channels,Kh, Kw)
# 使用nn.Parameter()包裹的属性才会出现在模型的parameters() 中；
conv.weight = nn.Parameter(w)  # 赋值
# 计算
y = conv(x)
y = y.data
#查看 y形状,输出通道数为 1,out_channels=1一致
print(y.shape)#(1, 1,280, 376)  
